package exercise;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;

public class TopicFilter implements Filter {

    private ArrayList<String> limitTopics;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //配置禁用词
        ArrayList<String> list = new ArrayList<>();
        list.add("苹果");
        list.add("香蕉");
        limitTopics = list;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //检查是否是从发表页面请求
        servletRequest.setCharacterEncoding("UTF-8");
        HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;
        String username = httpServletRequest.getParameter("username");
        System.out.println(username);
        if (username != null) {
            //校验禁用词
            String comment = httpServletRequest.getParameter("comment");
            System.out.println(comment);
            for (String limitTopic : limitTopics) {
                if (comment.contains(limitTopic)) {
                    System.out.println("检测到敏感词");
                    //将提示信息放入request对象
                    httpServletRequest.setAttribute("message", "~~有敏感词");
                    //转发到发表评论页面
                    httpServletRequest.getRequestDispatcher("/topic.jsp")
                            .forward(servletRequest, servletResponse);
                    return;
                }
            }
            System.out.println("没有检测到敏感词");
            //继续到目标
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            System.out.println("页面请求不合法!");
            //转发到发表评论页面
            httpServletRequest.getRequestDispatcher("/topic.jsp")
                    .forward(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
